package com.friend.chat.net

import com.friend.chat.BuildConfig
import com.friend.chat.base.NetUrlConstant.BASE_URL
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @des
 * @date 2021/9/24
 * @author gorilla
 */
object RetrofitCreator {
    private val myHttpClient by lazy {
        OkHttpClient.Builder()
            .connectTimeout(35, TimeUnit.SECONDS)
            .writeTimeout(35, TimeUnit.SECONDS)
            .readTimeout(35, TimeUnit.SECONDS)
            .addInterceptor(DiamondHeaderInterceptor())
            .addInterceptor(mDiamondLogIntercept())
            .addInterceptor(DiamondTokenInterceptor())
            .build()
    }

    private val myRetrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(myHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    val server: IServer = myRetrofit.create(IServer::class.java)


    private fun mDiamondLogIntercept(): HttpLoggingInterceptor {
        val logInterceptor = HttpLoggingInterceptor()
        if (BuildConfig.DEBUG) {
            logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            logInterceptor.level = HttpLoggingInterceptor.Level.NONE
        }
        return logInterceptor
    }

    class DiamondHeaderInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val requestBuilder = chain.request().newBuilder()
           /* for (item in getHeaders()) {
                requestBuilder.header(item.key, item.value)
            }*/
            return chain.proceed(requestBuilder.build())
        }
    }
}